package com.android.bind.components;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.android.bind.annotation.BindLayout;
import com.android.bind.annotation.BindView;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;

public class FragmentBind {
	private final static String FIND_VIEW_BY_ID = "findViewById";

	public static View bind(Fragment fragment, Context context) {
		if (fragment == null || context == null) {
			return null;
		}
		View view = bindLayout(fragment, context);
		bindViews(fragment, view);
		return view;
	}

	private static View bindLayout(Fragment fragment, Context context) {
		Class<? extends Fragment> clazz = fragment.getClass();
		BindLayout layout = (BindLayout) clazz.getAnnotation(BindLayout.class);
		if (layout == null) {
			return null;
		}
		int layoutId = layout.value();
		if (layoutId > 0) {
			return LayoutInflater.from(context).inflate(layoutId, null, false);
		}
		return null;
	}

	private static void bindViews(Fragment fragment, View view) {
		Class<? extends Fragment> clazz = fragment.getClass();
		Class<? extends View> viewClazz = view.getClass();
		Field[] fields = clazz.getDeclaredFields();
		if (fields != null && fields.length > 0) {
			for (Field field : fields) {
				field.setAccessible(true);
				BindView viewInject = field.getAnnotation(BindView.class);
				if (viewInject != null) {
					int viewId = viewInject.value();
					if (viewId > 0) {
						try {
							Method method = viewClazz.getMethod(
									FIND_VIEW_BY_ID, int.class);
							method.setAccessible(true);
							Object obj = method.invoke(viewClazz, viewId);
							field.set(fragment, obj);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	private static void bindEvent(Fragment fragment, View view) {
		EventManager.bindEvents(fragment, view);
	}

}
